package com.mzj.saas.jobs.backlog.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import com.mzj.saas.jobs.backlog.entity.BacklogItem;
import com.mzj.saas.jobs.backlog.entity.BacklogItemLock;
import com.mzj.saas.jobs.backlog.entity.SmartLock;
import com.mzj.saas.jobs.backlog.repository.BacklogItemLockRepository;
import com.mzj.saas.jobs.backlog.repository.BacklogItemRepository;
import com.mzj.saas.jobs.backlog.repository.SmartLockRepository;
import com.mzj.saas.jobs.backlog.vo.AuthVO;
import com.mzj.saas.jobs.commons.DateUtils;
import com.mzj.saas.jobs.commons.SqlUtils;
import com.mzj.saas.jobs.config.sms.SmsConfig;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 租金/押金待办事项
 */
@Service
public class BacklogBillService {
    private static Logger log = LoggerFactory.getLogger(BacklogBillService.class);

    @Value("${saas.service}")
    private String saasService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemLockRepository backlogItemLockRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmsConfig smsConfig;

    public String work() throws Exception {
        handleBillBacklog();
        return "SUCCESS";
    }

    public void handleBillBacklog() {
        try {
            log.info("BacklogBillService----->租金/押金待办事项");

            String billSql = "SELECT id,house_id AS houseId,org_id AS orgId,match_user_id AS matchUserId,charge_type AS chargeType,should_pay_time as shouldPayTime "
                    + "FROM saas_rent_bill WHERE payment_status = 0 AND "
                    + "STR_TO_DATE(NOW(),'%Y-%m-%d') >  STR_TO_DATE(should_pay_time,'%Y-%m-%d')";

            List<Map<String, Object>> infoList = jdbcTemplate.queryForList(billSql);

            if (CollectionUtils.isEmpty(infoList)) {
                log.info("BacklogBillService----->还没有账单超过缴费时间,无需提醒");
                return;
            }

            log.info("BacklogBillService----->账单超过缴费时间提醒 size = {}", infoList.size());

			Date date = new Date();
			List<String> houseIdIds = new ArrayList<>();
			// 账单
			List<Long> billIds = new ArrayList<>();
            infoList.forEach(info -> {
                Long id = Long.parseLong(info.get("id").toString());
                BacklogItemLock lock = backlogItemLockRepository.findBacklogItemLockByBillId(id);
                if (lock != null) {
                    log.info("BacklogBillService----->待办事项已存在该账单对应的数据, billId={}", id);
                    return;
                }

                BacklogItem item = backlogItemRepository.findByHouseIdAndTypeAndHandleStatus(
                        info.get("houseId").toString(), BacklogItemTypeEnum.RENT_BILL.getValue(), 0);
                if (item == null) {
                    String title = "租金/押金账单待缴费";
                    item = new BacklogItem();
                    item.setHouseId(info.get("houseId").toString());
                    item.setOrgId(Long.parseLong(info.get("orgId").toString()));
                    item.setTitle(title);
                    item.setContent("请尽快缴费，以防影响使用");
                    item.setBusinessStatus("(智能锁)已冻结");
                    item.setType(BacklogItemTypeEnum.RENT_BILL.getValue());
                    item.setHandleStatus(0);
                    item.setMatchUserId(info.get("matchUserId").toString());
                    item.setCreateTime(date);
                    backlogItemRepository.save(item);
                }

				lock = new BacklogItemLock();
				lock.setBacklogItemId(item.getId());
				lock.setBillId(id);
				lock.setMatchUserId(info.get("matchUserId").toString());
				backlogItemLockRepository.save(lock);
				houseIdIds.add(item.getHouseId());
				billIds.add(id);
			});
            log.info("BacklogBillService----->账单超过缴费时间冻结智能锁, 房屋信息, houseIdIds={}", JSON.toJSONString(houseIdIds));

			List<Long> lockIds = smartLockRepository.findByHouseIdIn(houseIdIds).stream().map(SmartLock::getId)
					.collect(Collectors.toList());
			Map<String, List<Long>> map = new HashMap<>();
			map.put("lockIds", lockIds);
			map.put("billIds", billIds);
			String url = saasService + "/device/freezeAllLock?type=job-executor-frozen";
			HttpEntity<Map<String, List<Long>>> requestEntity = new HttpEntity<Map<String, List<Long>>>(map);
			restTemplate.exchange(url.toString(), HttpMethod.POST, requestEntity, String.class);
            log.info("BacklogBillService----->账单超过缴费时间冻结智能锁, lockIds.size={}, map={}", lockIds.size(), JSON.toJSONString(map));

            //发送冻结提醒短信
            String sql = "SELECT mobile,house_id as houseId FROM saas_smart_lock_auth WHERE bind_type = 0 AND match_user_id = author_user_id AND house_id IN "
                    + SqlUtils.foreachIn(houseIdIds.size());
            List<AuthVO> auths = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AuthVO.class), houseIdIds.toArray());

            for (AuthVO auth : auths) {
                for (Map<String, Object> info : infoList) {
                    String mobile = auth.getMobile();
                    String authHouseId = auth.getHouseId();
                    String houseId = info.get("houseId").toString();
                    String shouldPayTime = "";
                    if (authHouseId.equals(houseId)) {
                        shouldPayTime = info.get("shouldPayTime").toString();
                    }

                    Integer days = DateUtils.daysBetween(DateUtils.convert(shouldPayTime, DateUtils.FORMAT_DATETIME_14), date);
                    String[] datas = {days.toString()};

                    String url2 = saasService + "/sms/datas?mobile=" + mobile + "&templateId=" + smsConfig.getFrozenTemplateCode();
                    HttpEntity<String[]> requestEntity2 = new HttpEntity<String[]>(datas);
                    restTemplate.exchange(url2, HttpMethod.POST, requestEntity2, String.class);
                    log.info("BacklogBillService-----> 发送短信通知成功, url2={}", url2);
                }
            }

        } catch (Exception e) {
            log.error("租金/押金待办事项异常  " + e.getMessage(), e);
        }
    }
}
